from demo import serializers
from demo import models

# 序列化相关
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response


"""
最终，http的method方法其实都可以不用写
"""
# 列表视图
class BookSerializerView(ModelViewSet):
    '''
    定义类视图
    '''
    # 指定查询集
    queryset = models.Book.objects.all()

    # 指定序列化器
    serializer_class = serializers.DrfBookSerializer

    # 额外功能
    # 列表视图自定义
    @action(methods=['get'], detail=False)
    def lastbook(self, request):
        # 获取最后一本书
        req = models.Book.objects.latest('id')
        s = self.get_serializer(req)
        return Response(s.data)

    # 详情视图自定义
    @action(methods=['put'], detail=True)
    def editbook(self, request, pk):
        book = self.get_object()
        book.price = request.data.get('price')
        book.save()
        serializer = self.get_serializer(book)
        return Response(serializer.data)


# 详情视图
class UserSerializerView(ModelViewSet):
    '''
    定义类视图
    '''
    # 指定查询集
    queryset = models.User.objects.all()

    # 指定序列化器
    serializer_class = serializers.DrfUserSerializer
